package br.jcrsistemas.util;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;

public class ValidDate {
	public static void main( String[] args ) {

		// dta valida
		System.out.println(ValidDate.isDateValid("03/21/2007"));

		// data invalida
		System.out.println(ValidDate.isDateValid("03/32/2007"));
	}

	public static boolean isDateValid( String date ) {
		StringTokenizer st = new StringTokenizer(date, " /:-,");
		String[] datePart = new String[st.countTokens()];
		int i = 0;
		int month, day, year;
		while (st.hasMoreTokens()) {
			datePart[i] = st.nextToken();
			i++;
		}
		try {
			if (datePart[0] != null)
				month = Integer.parseInt(datePart[0]);
			else
				return false;
			if (datePart[1] != null)
				day = Integer.parseInt(datePart[1]);
			else
				return false;
			if (datePart[2] != null) {
				if (datePart[2].length() < 4)
					return false;
				// invalida ano fora do formato YYYY
				year = Integer.parseInt(datePart[2]);
			} else {
				return false;
			}
			return isDateValid(year, month, day);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public static boolean isDateValid( int year, int month, int day ) {
		return isDateValid(year, month, day, 0, 0, 0);
	}
	
	public static boolean isDateValid( String year, String month, String day ) {
		return isDateValid(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day), 0, 0, 0);
	}

	public static boolean isDateValid( int year, int month, int day, int hour,
			int minute, int second ) {
		int testYear;
		int testMonth;
		int testDay;
		int testHour;
		int testMinute;
		int testSecond;
		// adjust month because January is equal to 0 in Gregorian Calendar
		month--;
		// instantiate a Gregorian Calendar object with Date to validate
		GregorianCalendar greg = new GregorianCalendar(year, month, day, hour,
				minute, second);
		testYear = greg.get(Calendar.YEAR);
		testMonth = greg.get(Calendar.MONTH);
		testDay = greg.get(Calendar.DATE);
		testHour = greg.get(Calendar.HOUR_OF_DAY); // use 24 hour clock
		testMinute = greg.get(Calendar.MINUTE);
		testSecond = greg.get(Calendar.SECOND);
		if (month != testMonth || day != testDay || year != testYear
				|| hour != testHour || minute != testMinute
				|| second != testSecond)
			return false;
		return true;
	}

}
